package com.df.happylearn.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.df.happylearn.R;
import com.df.happylearn.application.Constants;
import com.df.happylearn.model.ArticleContent;
import com.df.happylearn.request.DataRequest;
import com.df.happylearn.ui.view.utils.LoadStateUtil;
import com.df.happylearn.ui.view.utils.StateEnum;
import com.df.happylearn.utils.CssUtil;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;

public class ArticleContentActivity extends BaseActivity {
    
    @Bind(R.id.txtTitle)
    TextView txtTitle;
    @Bind(R.id.progressBar)
    ProgressBar progressBar;
    @Bind(R.id.webview)
    WebView mWebView;
    @Bind(R.id.loadFail)
    View loadFail;

    private int articleId;
    private String articleContent;
    private ArticleContent articleInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        articleId = intent.getIntExtra("articleId", 0);
        initView();
        getArticleContent();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_article_content;
    }

    private void initView() {
        mWebView.getSettings().setJavaScriptEnabled(true);
        // 添加js交互接口类，并起别名 imagelistner
        mWebView.addJavascriptInterface(new MyJavascriptInterface(this), "imagelistner");
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.setWebChromeClient(webChromeClient);
    }

    WebChromeClient webChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            progressBar.setProgress(newProgress);
            if (newProgress == 100) {
                hideProgressBar();
            } else {
                showProgressBar();
            }
            super.onProgressChanged(view, newProgress);
        }
    };

    // 遍历所有的img几点，并添加onclick函数，函数的功能是在图片点击的时候调用本地java接口并传递url过去
    String JAVASCRIPT_FUNCTION = "javascript:(function(){" +
            "var objs = document.getElementsByTagName(\"img\"); " +
            "var urls = new Array;" +
            "for(var i=0;i<objs.length;i++)  " +
            "{" +
            "urls[i] = objs[i].src;" +
            "    objs[i].onclick=function()  " +
            "    {  " +
            "        window.imagelistner.openImage(urls.toString(), this.src);  " +
            "    }  " +
            "}" +
            "})()";

    private void addImageClickListener() {
        mWebView.loadUrl(JAVASCRIPT_FUNCTION);
    }

    // js通信接口
    public class MyJavascriptInterface {

        private Context context;

        public MyJavascriptInterface(Context context) {
            this.context = context;
        }

        @JavascriptInterface
        public void openImage(String urls, String currentUrl) {
            Intent intent = new Intent();
            intent.putExtra("images", urls);
            intent.putExtra("current", currentUrl);
            intent.setClass(context, ShowWebImageActivity.class);
            context.startActivity(intent);
        }
    }

    // 监听
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            // html加载完成之后，添加监听图片的点击js函数
            addImageClickListener();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

    }

    private void getArticleContent() {
        Subscriber subscriber = new Subscriber<ArticleContent>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                hideProgressBar();
                LoadStateUtil.stateChange(mWebView, loadFail, StateEnum.LOAD_FAIL);
            }

            @Override
            public void onNext(ArticleContent data) {
                articleInfo = data;
                loadArticle(articleInfo);
                LoadStateUtil.stateChange(mWebView, loadFail, StateEnum.LOAD_SUCCESS);
            }
        };
        DataRequest.getInstance().getArticleContent(subscriber, articleId);
    }

    private void loadArticle(ArticleContent bean) {
        if (bean.getTitle().contains("_")) {
            String[] aa = bean.getTitle().split("_");
            articleContent = "<div class=time>" + aa[1] + " 浏览次数:" + bean.getViews() + "</div>" + bean.getContent();
            mWebView.loadData(CssUtil.getInstance().injectCss(articleContent), "text/html; charset=UTF-8", null);
            setTitle(aa[0]);
        } else {
            articleContent = "<div class=time>" + "Crazy studio" + " 浏览次数:" + bean.getViews() + "</div>" + bean.getContent();
            mWebView.loadData(CssUtil.getInstance().injectCss(articleContent), "text/html; charset=UTF-8", null);
            setTitle(bean.getTitle());
        }
    }

    @OnClick(R.id.back)
    void onBack() {
        onBackPressed();
    }

    @OnClick(R.id.txtReferesh)
    void refresh() {
        getArticleContent();
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra("article_id", articleId);
        setResult(Constants.ACTICLEACTIVITY_RESULT_CODE, intent);
        mWebView.destroy();
        super.onBackPressed();
    }

    private void setTitle(String title) {
        txtTitle.setText(title);
    }

    private void hideProgressBar() {
        progressBar.setVisibility(View.INVISIBLE);
    }

    private void showProgressBar() {
        progressBar.setVisibility(View.VISIBLE);
    }
}
